package br.com.rapidrest.demo.chain;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import br.com.rapidrest.chain.BasicChainContext;
import br.com.rapidrest.chain.Chain;
import br.com.rapidrest.chain.Command;
import br.com.rapidrest.exception.ChainException;
import br.com.rapidrest.util.RedirectUtil;

public class HolyPageRedirectCommand implements Command {

	@SuppressWarnings("unchecked")
	@Override
	public void execute(Chain chain) throws ChainException {
		BasicChainContext context = (BasicChainContext) chain.getContext();
		Object returnedValue = context.getReturnedValue();

		if (returnedValue instanceof Class) {
			String webPackage = context.getWebPackage();
			Class<?> pageClass = (Class<?>) returnedValue;
			if (pageClass.getName().startsWith(webPackage)) {
				HttpServletRequest request = context.getRequest();
				String targetMapping = RedirectUtil.getMapping(webPackage,
						pageClass);
				targetMapping = targetMapping.substring(1);
				request.setAttribute("redirect", targetMapping);
				try {
					RequestDispatcher requestDispatcher = request
							.getRequestDispatcher("/redirect.jsp");
					requestDispatcher.forward(request, context.getResponse());
				} catch (IOException e) {
					throw new ChainException(e);
				} catch (ServletException e) {
					throw new ChainException(e);
				}
				return;
			}
		}

		chain.proceed();
	}

}
